import json

from flask import Flask, request

import settings
from dinggroup import Robot
from message import ReceiveMessage, MessageHandler

app = Flask(__name__)


@app.route('/dingding/dinggroup', methods=['POST'])
def dinggroup():
    sign = request.headers.get('Sign')
    timestamp = request.headers.get('Timestamp')
    check_sign = Robot.check_sign(timestamp, settings.WISDOMLIFE_ROBOT_APP_SECRET)

    if sign == check_sign:
        message_dict = json.loads(request.data.decode('utf8'))
        msg_obj = ReceiveMessage(message=message_dict)
        msg_handler = MessageHandler(msg_obj)
        msg_handler.reply()
        return {'code': 0, 'detail': 'ok'}
    return {'code': -1, 'error': '非法sign'}


if __name__ == '__main__':
    app.run('0.0.0.0', debug=True)
